//
//  SecondRightViewController.m
//  项目A --半糖
//
//  Created by romana on 16/5/21.
//  Copyright © 2016年 romana. All rights reserved.
//

#import "SecondRightViewController.h"
#import "SecondHeadView.h"
#import "AFNetworking.h"
#import "MyCollectionReusableView.h"
#import "SecondRightModel.h"
#import "SecondRightCollectionViewCell.h"
#import "MJRefresh.h"

#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height

@interface SecondRightViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>

@property(nonatomic,strong)UICollectionView *myCollectionV;
@property(nonatomic,strong)NSMutableArray *myArray;
@property(nonatomic,strong)NSMutableArray *myArrayTwo;


@end

@implementation SecondRightViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor yellowColor];
    
    self.myArray = [NSMutableArray array];
    
    [self read];
  //  [self getData:0];
    
   // self.isUpLoading = NO;
    
//    // 2.集成上拉下拉功能
//    [self addHeader];
//    [self addFooter];
//    
        self.navigationController.navigationBar.translucent = NO;
    
//        SecondHeadView *secondHV = [[SecondHeadView alloc ]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 440)];
//        secondHV.backgroundColor = [UIColor whiteColor];
//        [self.view addSubview:secondHV];
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    //每个item的大小
    flowLayout.itemSize = CGSizeMake((WIDTH - 25) / 3, 120);
    flowLayout.minimumInteritemSpacing = 5;
    flowLayout.minimumLineSpacing = 5;
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 5, 30, 5);
    self.myCollectionV = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 64 - 49) collectionViewLayout:flowLayout];
    //   self.myCollection.pagingEnabled = YES;
    self.myCollectionV.showsHorizontalScrollIndicator = NO;
    self.myCollectionV.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.myCollectionV];
    
    
    [self.myCollectionV registerClass:[SecondRightCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    
    //添加头视图(高度)
    
    flowLayout.headerReferenceSize = CGSizeMake(self.view.frame.size.width, 390);
    
    
    self.myCollectionV.delegate = self;
    self.myCollectionV.dataSource = self;
    
    //注册头视图
    [self.myCollectionV registerClass:[MyCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"reuseHeader"];
    
    // 2.集成上拉下拉功能
    [self addHeader];
    [self addFooter];
    
    
    
    // Do any additional setup after loading the view.
}
#pragma mark --下拉刷新
- (void)addHeader
{
    //    __unsafe_unretained typeof(self) vc = self;
    
    __block SecondRightViewController *vc = self;//因为block块里用self会报警告,所以需要将self声明成block变量
    
    // 添加下拉刷新头部控件
    [self.myCollectionV addHeaderWithCallback:^{
        // 进入刷新状态就会回调这个Block
        
        vc.nextPage = 1;//记录页码的
        vc.isUpLoading = NO;//标记为下拉操作
        [vc getData:vc.nextPage];//重新请求数据
      //  NSLog(@"11111");
    }];
    
#pragma mark 自动刷新(一进入程序就下拉刷新)
    [self.myCollectionV headerBeginRefreshing];
    
}

#pragma mark --上拉加载更多
- (void)addFooter
{
    //    __unsafe_unretained typeof(self) vc = self;
    __block SecondRightViewController *vc = self;
    
    // 添加上拉刷新尾部控件
    [self.myCollectionV addFooterWithCallback:^{
        // 进入刷新状态就会回调这个Block
        
        vc.nextPage ++;
        vc.isUpLoading = YES;//标记为上拉操作
        [vc getData:vc.nextPage];//请求数据
        
    }];
}

-(void)read{
    
    
    self.myArrayTwo = [NSMutableArray array];
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    NSString *eventArrayPath = [path stringByAppendingPathComponent:@"SecondRighteventArray.txt"];
    NSArray *eventArray = [NSArray arrayWithContentsOfFile:eventArrayPath];
    if (eventArray.count != 0){
    
        for (NSDictionary *dic in eventArray) {
            SecondRightModel *model = [[SecondRightModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.myArrayTwo addObject:model];
        }
    }
        
        
        
        }


-(void)getData:(NSInteger)nextPage{
 
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
         [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/html", @"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", @"text/plain", @"application/x-javascript", @"application/javascript",nil]];
    NSString *string = [NSString stringWithFormat:@"%ld",nextPage];
    NSDictionary *dic = @{@"app_id":@"com.jzyd.BanTang",@"app_installtime":@"1434705307",@"app_versions":@"5.7",@"channel_name":@"appStore",@"client_id":@"bt_app_ios",@"client_secret":@"9c1e6634ce1c5098e056628cd66a17a5",@"oauth_token":@"8a11f2b3cd8fd625a8d8e9effb21dd0f",@"os_versions":@"9.3.1",@"page":string,@"pagesize":@"18",@"screensize":@"1242",@"track_device_info":@"iPhone7%2C1",@"track_deviceid":@"C2D3B460-4E0E-4639-A030-D274CFC43D50",@"track_user_id":@"125107",@"v":@"12"};
[manager POST:@"http://open3.bantangapp.com/community/post/hotRecommend?" parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
    
    
} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    
    NSMutableDictionary *bigDic = responseObject;
    
    
    NSMutableArray *dataArray = [bigDic objectForKey:@"data"];
    
    if (self.isUpLoading == NO) {
        //说明是下拉，就要清空数组中的数据
        [self.myArray removeAllObjects];
    }
    //缓存
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    NSString *eventArrayPath = [path stringByAppendingPathComponent:@"SecondRighteventArray.txt"];
    //(2)将数组写入文件
    [dataArray writeToFile:eventArrayPath atomically:YES];
    
    for (NSDictionary *dic in dataArray) {
        SecondRightModel *model = [[SecondRightModel alloc] init];
        [model setValuesForKeysWithDictionary:dic];
        [self.myArray addObject:model];
    }
    
    [self.myCollectionV footerEndRefreshing];
    [self.myCollectionV headerEndRefreshing];
    
    [self.myCollectionV reloadData];
    
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    
    
}];



}


-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        
        MyCollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"reuseHeader" forIndexPath:indexPath];
      //  headerView.backgroundColor = [UIColor redColor];
        
        return headerView;
    }else{
        
        UICollectionReusableView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"reuseFooter" forIndexPath:indexPath];
        footerView.backgroundColor = [UIColor orangeColor];
        return  footerView;
        
        
    }
    
}



-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{

    if (self.myArray.count == 0) {
        return  self.myArrayTwo.count;
    } else {
        return self.myArray.count;
    }
}


-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

    SecondRightCollectionViewCell *item = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    
    if (self.myArray.count == 0) {
        item.model = [self.myArrayTwo objectAtIndex:indexPath.row];

    } else {
        item.model = [self.myArray objectAtIndex:indexPath.row];

    }
    
   // item.backgroundColor = [UIColor redColor];
    return item;




}




@end
